// 切换语言组件
import { LANGUAGE_LIST } from '@/constants/publicConstant';
import { DownOutlined } from '@ant-design/icons';
import { getLocale, setLocale } from '@umijs/max';
import type { MenuProps } from 'antd';
import { Button, Dropdown, Space } from 'antd';
import * as dayjs from 'dayjs';
import 'dayjs/locale/en';
import 'dayjs/locale/zh-cn';
import 'dayjs/locale/zh-tw';
import { FC, useEffect, useMemo, useState } from 'react';

const LanguageBar: FC = () => {
  const [items, setItems] = useState<MenuProps['items']>([]);
  const currentLocale = getLocale();

  // 获取当前选中的语言信息
  const currentLanguage = useMemo(() => {
    for (const key in LANGUAGE_LIST) {
      const lang = LANGUAGE_LIST[key as keyof typeof LANGUAGE_LIST];
      if (lang.locale === currentLocale) {
        return lang;
      }
    }
    return LANGUAGE_LIST.CN; // 默认返回简体中文
  }, [currentLocale]);

  useEffect(() => {
    const temp: MenuProps['items'] = [];
    for (const key in LANGUAGE_LIST) {
      const { label, locale, flag } = LANGUAGE_LIST[key as keyof typeof LANGUAGE_LIST];
      temp.push({
        key: locale,
        label: (
          <span>
            {flag} {label}
          </span>
        ),
        disabled: locale === currentLocale, // 当前选中的语言置灰不可点击
      });
    }
    setItems(temp);
  }, [currentLocale]);

  // 切换语言
  const onClick: MenuProps['onClick'] = ({ key: locale }) => {
    // 使用 Umi 的 setLocale API，自动处理 localStorage
    setLocale(locale, true); // false 表示不刷新页面

    // dayjs 需要使用小写格式
    const dayjsLocaleMap: Record<string, string> = {
      'zh-CN': 'zh-cn',
      'zh-TW': 'zh-tw',
      'en-US': 'en',
    };

    const dayjsLocale = dayjsLocaleMap[locale] || 'en';
    dayjs.locale(dayjsLocale);
  };

  return (
    <Dropdown menu={{ items, onClick }}>
      <Button
        type="text"
        style={{
          margin: '0 .5rem',
          cursor: 'pointer',
          color: 'rgba(0, 0, 0, 0.65)',
        }}
      >
        <Space>
          <span style={{ fontSize: '16px' }}>{currentLanguage.flag}</span>
          <span>{currentLanguage.label}</span>
          <DownOutlined />
        </Space>
      </Button>
    </Dropdown>
  );
};

export default LanguageBar;
